package controllers

import (
	"backend/database"
	"log"
	"net/http"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

// 登录页面
func Login(c *gin.Context) {
	c.HTML(http.StatusOK, "login.html", nil)
}

// 登录处理
func LoginPost(c *gin.Context) {
	db := database.GetDB()

	email := c.PostForm("email")
	password := c.PostForm("password")

	if email == "" || password == "" {
		c.HTML(http.StatusBadRequest, "login.html", gin.H{
			"error": "邮箱或密码不能为空",
		})
		return
	}

	// 查询用户
	var user database.User
	err := db.Where("email = ? AND password = ?", email, password).First(&user).Error
	if err != nil {
		c.HTML(http.StatusBadRequest, "login.html", gin.H{
			"error": "邮箱或密码错误",
		})
		return
	}

	// 设置会话
	session := sessions.Default(c)
	session.Set("username", user.Username)
	session.Set("email", user.Email)
	session.Set("user_id", user.ID)

	// 检查是否有重定向URL
	redirectURL := session.Get("redirect_url")
	session.Delete("redirect_url")
	session.Save()

	// 重定向到之前的页面或首页
	if redirectURL != nil {
		c.Redirect(http.StatusFound, redirectURL.(string))
	} else {
		c.Redirect(http.StatusFound, "/")
	}
}

// 登录成功页面
func LoginSuccess(c *gin.Context) {
	c.HTML(http.StatusOK, "login_success.html", gin.H{
		"message": "登录成功！欢迎回来。",
	})
}

// 注册页面
func Register(c *gin.Context) {
	c.HTML(http.StatusOK, "register.html", nil)
}

// 注册处理
// 注册处理
func RegisterPost(c *gin.Context) {
	db := database.GetDB()

	// 获取表单数据
	username := c.PostForm("username")
	email := c.PostForm("email")
	password := c.PostForm("password")

	// 验证表单数据
	if username == "" || email == "" || password == "" {
		c.HTML(http.StatusBadRequest, "register.html", gin.H{
			"error": "用户名、邮箱或密码不能为空",
		})
		return
	}

	// 检查用户名是否已存在
	var count int64
	db.Model(&database.User{}).Where("username = ?", username).Count(&count)
	if count > 0 {
		c.HTML(http.StatusBadRequest, "register.html", gin.H{
			"error": "用户名已经存在",
		})
		return
	}

	// 检查邮箱是否已存在
	db.Model(&database.User{}).Where("email = ?", email).Count(&count)
	if count > 0 {
		c.HTML(http.StatusBadRequest, "register.html", gin.H{
			"error": "邮箱已经存在",
		})
		return
	}

	// 插入新用户
	user := database.User{
		Username: username,
		Email:    email,
		Password: password,
	}
	if err := db.Create(&user).Error; err != nil {
		log.Println(err)
		c.HTML(http.StatusInternalServerError, "register.html", gin.H{
			"error": "用户创建失败",
		})
		return
	}

	// 同步插入 user_statues 初始记录
	userStatues := database.User_statues{
		UserID:   user.ID,
		Username: user.Username,
	}
	if err := db.Create(&userStatues).Error; err != nil {
		log.Println(err)
		c.HTML(http.StatusInternalServerError, "register.html", gin.H{
			"error": "用户资料初始化失败",
		})
		return
	}

	// 注册成功，跳转到登录页面
	c.Redirect(http.StatusFound, "/login")
}

// 退出登录
func Logout(c *gin.Context) {
	session := sessions.Default(c)
	session.Clear()
	session.Save()
	c.Redirect(http.StatusFound, "/login")
}
